from django.http import HttpResponse, JsonResponse
from django.http.response import HttpResponseRedirect
from django.contrib import auth
from django.shortcuts import render, redirect
from bbs.models import Announcement, User, Topic, Kind, Reply, Like
from bbs.forms import MDEditorForm
from fileshare.models import Post
from multichat.models import Room
from friendship.models import Friend, FriendshipRequest
from django.views.decorators.csrf import csrf_exempt
from django.conf import settings
import markdown

# 主页
def home(request):
    if request.method == 'GET':
        response = {}

        # top 10（公告）的处理，筛选10个也要改
        announcements = Announcement.objects.filter()
        # 把这10个公告封装成字典
        a_list = []
        for a in announcements:
            dic = {'a_id': a.id, 'a_title': a.a_title}
            a_list.append(dic)
        # 把列表装进回复字典里
        n = 10 if len(a_list) < 10 else len(a_list)

        response['a_list'] = a_list[::-1][0:n-1]

        # 帖子推荐列表，推荐8个帖子，推荐8个要改
        recommends = Topic.objects.filter(recommend=True)
        # 推荐列表
        r_list = []

        for t in recommends:
        
            t_like_type = 'no'
            try:
                t_like_type = Like.objects.get(tid=t.id, uid=request.user).like
            except:
                pass
            r_list.append({
                't_title':t.t_title, 
                't_uid':t. t_uid, 
                't_introduce': t.t_introduce,
                't_content':t.t_content,
                't_id':t.id,
                't_like': Like.objects.filter(tid=t.id, like=True).count(),
                't_dislike':Like.objects.filter(tid=t.id, like=False).count(),
                't_like_type':t_like_type,
                })

        # 把列表装进response
        response['r_list'] = r_list

        # 把username装进返回字典里
        response['uid'] = request.user.username
        # 头像字段
        try:
            response['uavatar'] = request.user.avatar.url
        except:
            pass
        # 把所有类别装入返回字典里
        kinds = Kind.objects.filter()
        response['kinds'] = kinds

        return render(request, 'home.html', response)


# 所有帖子

def all_tie(request, kid, reply_limit, time_limit):
    uid = request.user

    if request.method == 'GET':
        kinds = Kind.objects.filter()
        topic_all = []
        if kid == '0' and reply_limit == '0' and time_limit == '0':
            # 默认时间排序把帖子传过去
            topics = Topic.objects.filter()
            for t in topics:
                t_like_type = 'no'
                try:
                    t_like_type = Like.objects.get(tid=t.id, uid=uid).like
                except:
                    pass
                topic_all.append({
                    't_title':t.t_title, 
                    't_uid':t. t_uid, 
                    't_introduce': t.t_introduce,
                    't_content':t.t_content,
                    'id':t.id,
                    't_like': Like.objects.filter(tid=t.id, like=True).count(),
                    't_dislike':Like.objects.filter(tid=t.id, like=False).count(),
                    't_like_type':t_like_type,
                    })
        else:
            # request.path_info   # 获取当前url
            # from django.urls import reverse
            # reverse('all_tie', kwargs={'kid': '0', 'reply_limit': '0', 'time_limit': '0'})

            topics = Topic.objects.filter()

            # 筛选分类
            if kid != '0':
                topics = Topic.objects.filter(t_kind=kid)

            # 筛选回复数量
            tmp = []
            for topic in topics:
                # 查看每个帖子的回复数量
                count = len(Reply.objects.filter(r_tid=topic.id))
                # print(count)
                print(reply_limit)
                if reply_limit == '0':
                    pass
                elif reply_limit == '1':  # 1是大于100
                    print('到1了')
                    if count < 100:
                        print('到了')
                        continue
                elif reply_limit == '2':  # 2是30-100
                    if count < 30 or count > 100:
                        continue
                elif reply_limit == '3':  # 3是小于30
                    if count > 30:
                        continue
                tmp.append(topic)
            topics = tmp

            # 筛选发布时间
            tmp = []
            for topic in topics:
                if time_limit == '0':  # 0是全部时间
                    pass
                elif time_limit == '1':   # 1是1个月内
                    # 如果在限制之前，就筛掉
                    pass
                elif time_limit == '2':   # 2是3个月内
                    # 如果在限制之前，就筛掉
                    pass
                elif time_limit == '3':   # 3是6个月内
                    # 如果在限制之前，就筛掉
                    pass
                elif time_limit == '4':   # 4是1年内
                    # 如果在限制之前，就筛掉
                    pass
                tmp.append(topic)
            topics = tmp

            for t in topics:
                t_like_type = 'no'
                try:
                    t_like_type = Like.objects.get(tid=t.id, uid=uid).like
                except:
                    pass
                topic_all.append({
                    't_title':t.t_title, 
                    't_uid':t. t_uid, 
                    't_introduce': t.t_introduce,
                    't_content':t.t_content,
                    'id':t.id,
                    't_like': Like.objects.filter(tid=t.id, like=True).count(),
                    't_dislike':Like.objects.filter(tid=t.id, like=False).count(),
                    't_like_type':t_like_type,
                    })

        response = {
            'topics': topic_all,
            'kinds': kinds,
            'kid': kid,
            'time_limit': time_limit,
            'reply_limit': reply_limit,
            'uid': uid,
            'uavatar': request.user.avatar.url,
        }

        return render(request, 'all.html', response)

    elif request.method == 'POST':
        # 搜索接收一个字段，查询标题或者简介里有关键字的帖子
        keys = request.POST.get('keys')
        # 按关键字查询标题里含有关键字的
        topics = Topic.objects.filter(t_title__icontains=keys)

        kinds = Kind.objects.filter()
        return render(request, 'all.html', {'topics': topics, 'kinds': kinds, 'uid': uid})


# 登录
def login(request):
    if request.method == 'GET':
        return render(request, 'login.html')
    elif request.method == 'POST':
        response1 = {
            'result': True,
            'msg': '错误, 请重试'
        }
        # 验证用户名密码是否正确，然后登陆存入session
        uid = request.POST.get('uid')
        pwd = request.POST.get('pwd')
        user = auth.authenticate(username=uid, password=pwd)
        if user:
            try:
                auth.login(request, user)
                request.session['uid'] = uid
            except:
                response1['msg'] = '登陆失败, 请检查用户名或密码.'
                return render(request, 'login.html', response1)

            response = {}

            # top 10（公告）的处理，筛选10个也要改
            announcements = Announcement.objects.filter()
            # 把这10个公告封装成字典
            a_list = []
            for a in announcements:
                dic = {'a_id': a.id, 'a_title': a.a_title}
                a_list.append(dic)
            # 把列表装进回复字典里
            n = 10 if len(a_list) < 10 else len(a_list)

            response['a_list'] = a_list[::-1][0:n-1]

            # 帖子推荐列表，推荐8个帖子，推荐8个要改
            recommends = Topic.objects.filter(recommend=True)
            # 推荐列表
            r_list = []

            for t in recommends:
                t_like_type = 'no'
                try:
                    t_like_type = Like.objects.get(tid=t.id, uid=request.user).like
                except:
                    pass
                r_list.append({
                    't_title':t.t_title, 
                    't_uid':t. t_uid, 
                    't_introduce': t.t_introduce,
                    't_content':t.t_content,
                    't_id':t.id,
                    't_like': Like.objects.filter(tid=t.id, like=True).count(),
                    't_dislike':Like.objects.filter(tid=t.id, like=False).count(),
                    't_like_type':t_like_type,
                    })
            # 把列表装进response
            response['r_list'] = r_list

            # 把uid装进返回字典里
            response['uid'] = request.session['uid']
            # 把所有类别装入返回字典里
            kinds = Kind.objects.filter()
            response['kinds'] = kinds

            return HttpResponseRedirect('/home/')

        else:
            response1['msg'] = '登陆失败, 请重试.'
            return render(request, 'login.html', response1)


# 登出
def logout(request):
    if request.method == 'GET':
        auth.logout(request)
        return redirect('/login')


# 注册
def register(request):
    if request.method == 'GET':
        return render(request, 'register.html')
    if request.method == 'POST':
        # 判断是否已有
        uid = request.POST.get('uid')
        pwd = request.POST.get('pwd')
        try:
            User.objects.create_user(username=uid, password=pwd)
        except Exception as e:
            print(e)
            return render(request, 'register.html', {'result': True, 'msg': '注册失败,请重试.'})
        return HttpResponseRedirect('/login/')


def user_info(request):
    if request.method == 'GET':
        user = User.objects.get(id=request.user.id)
        topics = Topic.objects.filter(t_uid=user)
        data = []
        for i in topics:
            data.append({'id': i.id, 'title': i.t_title,
                        'introduce': i.t_introduce})
        response = {
            'topics': data,
        }
        return render(request, 'user-info.html', response)


# 发布页
def publish(request):
    if request.method == 'GET':
        form = MDEditorForm()
        kinds = Kind.objects.filter()
        response = {
            'kinds': kinds,
            'form': form,
            'result': False
        }
        return render(request, 'publish.html', response)
    elif request.method == 'POST':
        # session获取uid
        uid = User.objects.get(id=request.user.id)
        # 提交发布的文章
        t_title = request.POST.get('t_title')
        t_introduce = request.POST.get('t_introduce')
        t_content = request.POST.get('t_content')
        t_kind = Kind.objects.get(id=request.POST.get('t_kind'))
        response2 = {
            'kinds': Kind.objects.filter(),
            'msg': '',
            'result': True
        }
        for _ in settings.SENSITIVE_WORD:
            if _ in t_title:
                response2['msg'] = '标题存在敏感信息{0}, 请修改后重试.'.format(_)
                return render(request, 'publish.html', response2)
        for _ in settings.SENSITIVE_WORD:
            if _ in t_introduce:
                response2['msg'] = '简介存在敏感信息{0}, 请修改后重试.'.format(_)
                return render(request, 'publish.html', response2)
        for _ in settings.SENSITIVE_WORD:
            if _ in t_content:
                response2['msg'] = '内容存在敏感信息{0}, 请修改后重试.'.format(_)
                return render(request, 'publish.html', response2)   

        obj = Topic.objects.create(t_title=t_title, t_introduce=t_introduce,
                                   t_content=t_content, t_kind=t_kind, t_uid=uid)
        t_id = obj.id

        # 存帖子图片
        # t_photo = request.FILES.get('t_photo', None)
        # t_photo_path = 'static/img/t_photo/' + str(t_id) + '_' + t_photo.name

        # if t_photo:
        #     # 保存文件
        #     import os
        #     f = open(os.path.join(t_photo_path), 'wb')
        #     for line in t_photo.chunks():
        #         f.write(line)
        #     f.close()

        # # 吧图片路径存入数据库
        # Topic.objects.filter(id=t_id).update(t_photo='/'+t_photo_path)

        return redirect('/single/' + str(t_id))


# 单个帖子页面
def single(request, tid):
    if request.method == 'GET':
        # 帖子内容
        # 时间类别作者，标题，正文，图片path
        try:
            topic = Topic.objects.get(id=tid)
        except Exception as e:
            return redirect('/home')

        t_time = topic.create_time
        t_kind = topic.t_kind
        t_title = topic.t_title
        t_content = markdown.markdown(topic.t_content,
                                  extensions=[
                                     'markdown.extensions.extra',
                                     'markdown.extensions.codehilite',
                                     'markdown.extensions.toc',
                                     'codehilite'
                                  ])
        t_uid = topic.t_uid
        t_introduce = topic.t_introduce
        uid = request.user
        admin_uid = request.session.get('admin_uid')
        t_uavatar = t_uid.avatar.url
        t_like_type = 'no'
        try:
            t_like_type = Like.objects.get(tid=topic, uid=request.user).like
        except:
            pass
        response = {
            'tid': tid,
            't_uid': t_uid,
            't_time': t_time,
            't_kind': t_kind,
            't_title': t_title,
            't_content': t_content,
            't_introduce': t_introduce,
            't_like': Like.objects.filter(tid=topic, like=True).count(),
            't_dislike':Like.objects.filter(tid=topic, like=False).count(),
            't_like_type':t_like_type,
            'uid': uid,
            't_uavatar': t_uavatar,
            'uavatar': request.user.avatar.url,
            'admin_uid': admin_uid,
        }

        # 留言内容
        # 留言者，留言时间，留言内容
        replys = Reply.objects.filter(r_tid=tid)
        reply_list = []
        for reply in replys:
            single_reply = {
                'r_uid': reply.r_uid,
                'r_time': reply.r_time,
                'r_content': reply.r_content,
                'r_id': reply.id,
                'r_photo': reply.r_photo,
                'r_uavatar': reply.r_uid.avatar.url,
            }

            reply_list.append(single_reply)
        response['reply_list'] = reply_list

        return render(request, 'single.html', response)

    elif request.method == 'POST':
        # 判断是否登录
        uid = request.session.get('uid')
        user = User.objects.get(id=request.user.id)
        topic = Topic.objects.get(id=tid)
        # 删除回复，管理员才可以删除
        # p_type = request.POST.get('type')
        # print(p_type)
        # if p_type == 'delete':
        #     response = {'msg': '', 'status': False}
        #     r_id = request.POST.get('r_id')
        #     Reply.objects.filter(id=r_id).delete()
        #     response['status'] = True
        #     # return HttpResponse(json.dumps(response))
        #     return JsonResponse(response)

        if not uid:
            return redirect('/login')
        # 进行回复
        r_content = request.POST.get('r_content')

        # 提交数据库
        obj = Reply.objects.create(
            r_tid=topic, r_uid=user, r_content=r_content)

        r_id = str(obj.id)
        r_photo = request.FILES.get('r_photo')
        r_photo_path = ''
        if r_photo:
            # 保存文件
            r_photo_path = 'static/img/r_photo/' + r_id + '_' + r_photo.name
            import os
            f = open(os.path.join(r_photo_path), 'wb')
            for line in r_photo.chunks():
                f.write(line)
            f.close()

        # 吧图片路径存入数据库
        Reply.objects.filter(id=r_id).update(r_photo='/'+r_photo_path)
        return redirect('/single/' + tid)


# 修改密码页面
def edit_pwd(request):
    if request.method == 'GET':
        uid = request.session.get('uid')
        return render(request, 'edit-pwd.html', {'uid': uid, 'uavatar': request.user.avatar.url})

    if request.method == 'POST':
        uid = request.session.get('uid')
        old = request.POST.get('old_pwd')
        new1 = request.POST.get('new_pwd1')
        new2 = request.POST.get('new_pwd2')
        response = {'msg': '', 'status': False}
        if new1 == new2:
            user = auth.authenticate(username=uid, password=old)
            if user:
                user.set_password(new1)
                user.save()
                response['status'] = True
                return JsonResponse(response)
            else:
                response['msg'] = '原密码错误'
                return JsonResponse(response)
        else:
            response['msg'] = '两次密码错误'
            return JsonResponse(response)


def edit_user_info(request):
    if request.method == 'GET':
        return render(request, 'edit-user-info.html')

    if request.method == 'POST':
        faculty = request.POST.get('faculty')
        major = request.POST.get('major')
        sex = request.POST.get('sex')
        age = request.POST.get('age')
        profile = request.POST.get('profile')
        pwd = request.POST.get('pwd')
        avatar = request.FILES.get('avatar', None)

        response = {'msg': '', 'status': False}
        print(request.user.username, pwd)
        user = auth.authenticate(username=request.user.username, password=pwd)
        if user:
            if faculty:
                user.faculty = faculty
            if major:
                user.major = major
            if sex:
                user.sex = sex
            if age:
                user.age = int(age)
            if profile:
                user.profile = profile
            if avatar:
                user.avatar = avatar

            user.save()
            response['status'] = True
            return JsonResponse(response)
        else:
            response['msg'] = '原密码错误'
            return JsonResponse(response)


# 管理员登录
def admin(request):
    if request.method == 'GET':
        return render(request, 'admin.html')
    elif request.method == 'POST':
        admin_uid = request.POST.get('admin_id')
        admin_pwd = request.POST.get('admin_pwd')

        response = {'msg': '', 'status': False}

        if admin_uid == 'guanliyuan' and admin_pwd == '123456':
            # 管理员登录成功
            response['status'] = True
            request.session['admin_uid'] = 'guanliyuan'
            # return HttpResponse(json.dumps(response))
            return JsonResponse(response)
        else:
            response['msg'] = '用户名或者密码错误'
            # return HttpResponse(json.dumps(response))
            return JsonResponse(response)


# 公告管理
def announcement(request):
    if not request.session.get('admin_uid'):
        return redirect('/my-admin')

    # 查询所有公告
    if request.method == 'GET':

        announcements = Announcement.objects.filter()
        response = {'announcements': announcements}
        return render(request, 'announcement.html', response)

    # 发公告，删公告
    elif request.method == 'POST':
        p_type = request.POST.get('type')
        response = {'msg': '', 'status': False}
        if p_type == 'delete':
            a_id = request.POST.get('a_id')
            Announcement.objects.filter(id=a_id).delete()
            response['status'] = True
        elif p_type == 'create':
            # 添加一条公告
            a_title = request.POST.get('a_title')
            a_content = request.POST.get('a_content')
            Announcement.objects.create(a_title=a_title, a_content=a_content)
            response['status'] = True
        # return HttpResponse(json.dumps(response))
        return JsonResponse(response)


# 帖子管理：标题，简介，时间，
def topic_manage(request):
    if not request.session.get('admin_uid'):
        return redirect('/my-admin')

    if request.method == 'GET':
        topics = Topic.objects.filter()
        response = {
            'topics': topics,
        }
        return render(request, 'admin-home.html', response)
    elif request.method == 'POST':
        p_type = request.POST.get('type')
        response = {'msg': '', 'status': False}
        print(p_type)
        # 删除帖子
        if p_type == 'delete':
            t_id = request.POST.get('t_id')
            Topic.objects.filter(id=t_id).delete()
            response['status'] = True
        # 置顶（推荐）
        if p_type == 'zhiding':
            print('置顶')
            t_id = request.POST.get('t_id')
            Topic.objects.filter(id=t_id).update(recommend=True)
            response['status'] = True
        # 取消置顶（推荐）
        if p_type == 'qzhiding':
            t_id = request.POST.get('t_id')
            Topic.objects.filter(id=t_id).update(recommend=False)
            response['status'] = True
        # return HttpResponse(json.dumps(response))
        return JsonResponse(response)


# 类别管理（板块管理）
def kind_manage(request):
    # 验证登录
    if not request.session.get('admin_uid'):
        return redirect('/my-admin')

    if request.method == 'GET':
        # get返回所有类别（板块）
        kinds = Kind.objects.filter()
        response = {
            'kinds': kinds,
        }
        return render(request, 'kind-manage.html', response)
    if request.method == 'POST':
        p_type = request.POST.get('type')
        response = {'msg': '', 'status': False}
        # 删除类别
        if p_type == 'delete':
            k_id = request.POST.get('k_id')
            Kind.objects.filter(id=k_id).delete()
            response['status'] = True

        # 添加类别
        if p_type == 'create':
            k_name = request.POST.get('k_name')
            Kind.objects.create(k_name=k_name)
            response['status'] = True

        # return HttpResponse(json.dumps(response))
        return JsonResponse(response)

# 共享文件管理
def file_manage(request):
    # 验证登录
    if not request.session.get('admin_uid'):
        return redirect('/my-admin')

    if request.method == 'GET':
        posts = Post.objects.filter()
        response = {
            'posts': posts,
        }
        return render(request, 'file-manage.html', response)
    if request.method == 'POST':
        p_type = request.POST.get('type')
        response = {'msg': '', 'status': False}
        if p_type == 'delete':
            p_id = request.POST.get('p_id')
            Post.objects.filter(id=p_id).delete()
            response['status'] = True
        elif p_type == 'allow':
            p_id = request.POST.get('p_id')
            Post.objects.filter(id=p_id).update(allow=True)
            response['status'] = True
        elif p_type == 'disallow':
            p_id = request.POST.get('p_id')
            Post.objects.filter(id=p_id).update(allow=False)
            response['status'] = True
        return JsonResponse(response)

# 房间管理
def room_manage(request):
    if not request.session.get('admin_uid'):
        return redirect('/my-admin')

    if request.method == 'GET':
        rooms = Room.objects.filter()
        response = {
            'rooms': rooms,
        }
        return render(request, 'room-manage.html', response)
    if request.method == 'POST':
        p_type = request.POST.get('type')
        response = {'msg': '', 'status': False}
        if p_type == 'delete':
            r_id = request.POST.get('r_id')
            Room.objects.filter(id=r_id).delete()
            response['status'] = True

        if p_type == 'create':
            r_name = request.POST.get('r_name')
            Room.objects.create(title=r_name)
            response['status'] = True
        return JsonResponse(response)

# 公告页面
def single_an(request, aid):
    if request.method == 'GET':
        try:
            an = Announcement.objects.get(id=aid)
        except Exception as e:
            return '/home'
        a_title = an.a_title
        a_content = an.a_content

        response = {
            'a_title': a_title,
            'a_content': a_content,
        }
        return render(request, 'single-an.html', response)

@csrf_exempt
def manage_blog(request):
    if request.method == 'GET':
        user = User.objects.get(id=request.user.id)
        topics = Topic.objects.filter(t_uid=user)
        data = []
        for i in topics:
            data.append({'id': i.id, 'title': i.t_title,
                        'introduce': i.t_introduce})
        response = {
            'topics': data,
        }
        return JsonResponse(response)

    elif request.method == 'POST':
        p_type = request.POST.get('type')
        response = {'msg': '', 'status': False}
        print(p_type)
        # 删除帖子
        if p_type == 'delete':
            t_id = request.POST.get('t_id')
            Topic.objects.filter(id=t_id).delete()
            response['status'] = True
        return JsonResponse(response)

@csrf_exempt
def get_friends(request):
    if request.method == 'GET':
        users = Friend.objects.friends(request.user)
        print(users)
        data = []
        for user in users:
            data.append({'id': user.id, 'username': user.username, 'faculty': user.faculty,
                        'major': user.major, 'sex': user.sex, 'age': user.age, 'profile': user.profile})
        response = {
            'friends': data
        }
        return JsonResponse(response)
    if request.method == 'POST':
        response = {'msg': '', 'status': False}
        other_id = request.POST.get('other_id')
        other_user = User.objects.get(id=other_id)
        try:
            # Friend.objects.get(from_user_id=request.user.id, to_user_id=other_user.id).delete()
            # Friend.objects.get(from_user_id=other_user.id, to_user_id=request.user.id).delete()
            Friend.objects.remove_friend(request.user, other_user)
            response['status'] = True
        except:
            response['msg'] = '删除失败'
        return JsonResponse(response)

@csrf_exempt
def add_friend(request):
    if request.method == 'GET':
        other_username = request.GET.get('other_username')
        print(other_username)
        other_users = User.objects.filter(username=other_username)
        data = []
        for user in other_users:
            data.append({'id': user.id, 'username': user.username, 'faculty': user.faculty,
                        'major': user.major, 'sex': user.sex, 'age': user.age, 'profile': user.profile})
        response = {
            'friends': data
        }
        return JsonResponse(response)
    
    if request.method == 'POST':
        other_id = request.POST.get('other_id')
        message = request.POST.get('message')
        print(other_id, message)
        other_user = User.objects.get(id=other_id)
        response = {'msg': '', 'status': False}
        try:
            Friend.objects.add_friend(request.user, other_user, message=message)
            response['status'] = True
        except:
            response['msg'] = '发送好友申请失败'
            return JsonResponse(response)
        return JsonResponse(response)


@csrf_exempt
def get_request(request):
    if request.method == 'GET':
        users = Friend.objects.unread_requests(user=request.user)
        data = []
        response = {'friends': data}
        if users == []:
            return JsonResponse(response)
        for user in users:
            data.append({'id': user.from_user.id, 'username': user.from_user.username, 'faculty': user.from_user.faculty,
                        'major': user.from_user.major, 'sex': user.from_user.sex, 'age': user.from_user.age, 'profile': user.from_user.profile})

        return JsonResponse(response)
    if request.method == 'POST':
        other_id = request.POST.get('other_id')
        other_user = User.objects.get(id=other_id)
        response = {'msg': '', 'status': False}
        if request.POST.get('type') == 'agree': 
            try:
                friend_request = FriendshipRequest.objects.get(from_user=other_user, to_user=request.user)
                friend_request.accept()
                response['status'] = True
            except:
                response['msg'] = '添加失败'
                return JsonResponse(response)

        if request.POST.get('type') == 'refusal': 
            try:
                friend_request = FriendshipRequest.objects.get(from_user=other_user, to_user=request.user)
                print(friend_request)
                friend_request.cancel()
                response['status'] = True
            except:
                response['msg'] = '拒绝失败'
                return JsonResponse(response)

        return JsonResponse(response)

def like(request):
    if request.method == 'POST':
        uid = request.user
        tid = Topic.objects.get(id=request.POST.get('tid'))
        like = True if request.POST.get('like')=='like' else False
        response = {
            'result': False,
            'msg':''
        }
        try:
            if not Like.objects.filter(uid=uid, tid=tid).count():
                like = Like.objects.create(uid=uid, tid=tid, like=like)
                response['result'] = True
            else:
                response['msg'] = '你已经点过了, 请勿重复点击.'
        except:
            response['msg'] = 'error.'
        return JsonResponse(response)

